package com.zhhtech.zhh.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.method.Touch;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatTextView;

import com.zhhtech.zhh.ui.utils.Logger;
import com.zhhtech.zhh.ui.utils.Logger;

import java.util.List;


/**
 * Created by zhoucl on 2018/11/21 0021.
 */
public class ContactTextView extends AppCompatTextView {
    private static final String THREE_DOTS = "...";
    private static final int THREE_DOTS_LENGTH = THREE_DOTS.length();
    private volatile boolean enableEllipsizeWorkaround = true;
    private SpannableStringBuilder spannableStringBuilder;

    boolean linkHit;

    public ContactTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public ContactTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ContactTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        setHighlightColor(Color.TRANSPARENT);
        setMovementMethod(LocalLinkMovementMethod.getInstance());
    }

    @Override
    public boolean performClick() {
        if (linkHit) {
            return true;
        }
        return super.performClick();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        linkHit = false;
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            if (enableEllipsizeWorkaround && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                final Layout layout = getLayout();
                if (layout.getLineCount() >= getMaxLines()) {
                    CharSequence charSequence = getText();
                    int lastCharDown = layout.getLineVisibleEnd(getMaxLines() - 1);
                    if (lastCharDown >= THREE_DOTS_LENGTH && charSequence.length() > lastCharDown) {
                        if (spannableStringBuilder == null) {
                            spannableStringBuilder = new SpannableStringBuilder();
                        } else {
                            spannableStringBuilder.clear();
                        }
                        spannableStringBuilder.append(charSequence.subSequence(0, lastCharDown - 1)).append(THREE_DOTS);
                        setText(spannableStringBuilder);
                    }
                }
            }
        } catch (Exception e) {
            Logger.e(e);
        }
        super.onDraw(canvas);
    }

    /**
     * 注意：spannableString 设置Spannable 的对象到spannableString中时，要用Spannable.SPAN_EXCLUSIVE_EXCLUSIVE的flag值，不然可能会会出现后面的衔接字符串不会显示
     */
    /*@Override
    protected void onDraw(Canvas canvas) {
        try {
            CharSequence charSequence = getText();
            int lastCharDown = getLayout().getLineVisibleEnd(0);
            if (charSequence.length() > lastCharDown) {
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
                spannableStringBuilder.append(charSequence.subSequence(0, lastCharDown - 4)).append("...");
                setText(spannableStringBuilder);
            }
        } catch (Exception e) {
            Logger.e(e);
        }
        super.onDraw(canvas);
    }*/
    public static SpannableStringBuilder createText(String text) {
        return new SpannableStringBuilder(text);
    }

    public static void setText(ContactTextView contactTextView, String text, List<UnSpanText> spanTexts, OnClickListener onClickListener) {
        SpannableStringBuilder spannableStringBuilder = createText(text);
        if (spanTexts != null)
            for (UnSpanText unSpanText : spanTexts)
                insertClickSpan(spannableStringBuilder, unSpanText, onClickListener);
        contactTextView.setText(spannableStringBuilder);
    }

    public static void insertClickSpan(SpannableStringBuilder spannableStringBuilder, UnSpanText unSpanText, OnClickListener onClickListener) {
        try {
            if (unSpanText.getStart() > spannableStringBuilder.length() || unSpanText.getEnd() > spannableStringBuilder.length())
                return;
            spannableStringBuilder.setSpan(new BpClickableSpan(unSpanText, onClickListener), unSpanText.getStart(), unSpanText.getEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    public static class LocalLinkMovementMethod extends LinkMovementMethod {
        static LocalLinkMovementMethod sInstance;


        public static LocalLinkMovementMethod getInstance() {
            if (sInstance == null)
                sInstance = new LocalLinkMovementMethod();

            return sInstance;
        }

        @Override
        public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
            int action = event.getAction();

            if (action == MotionEvent.ACTION_UP ||
                    action == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();

                x -= widget.getTotalPaddingLeft();
                y -= widget.getTotalPaddingTop();

                x += widget.getScrollX();
                y += widget.getScrollY();

                Layout layout = widget.getLayout();
                int line = layout.getLineForVertical(y);
                int off = layout.getOffsetForHorizontal(line, x);

                android.text.style.ClickableSpan[] link = buffer.getSpans(off, off, android.text.style.ClickableSpan.class);

                if (link.length != 0) {
                    if (action == MotionEvent.ACTION_UP) {
                        link[0].onClick(widget);
                    } else if (action == MotionEvent.ACTION_DOWN) {
                        Selection.setSelection(buffer,
                                buffer.getSpanStart(link[0]),
                                buffer.getSpanEnd(link[0]));
                    }

                    if (widget instanceof ContactTextView) {
                        ((ContactTextView) widget).linkHit = true;
                    }
                    return true;
                } else {
                    Selection.removeSelection(buffer);
                    super.onTouchEvent(widget, buffer, event);
                    return false;
                }
            }
            return Touch.onTouchEvent(widget, buffer, event);
        }
    }
}